package com.example.springbootdemo.异步注解失效测试.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author forsake
 * @Description  线程池配置类
 * @Date 15:49 2021/8/30
 **/
@Configuration
public class ExecutorsConfig {
    /**
     * 核心线程数为cup的核心数
     */
    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();
    /**
     * 最大线程数为两倍的cpu的核心数
     */
    private static final int MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2 + 1;
    /**
     * 默认存活时间
     */
    private static final int KEEP_ALIVE_TIME = 30;
    /**
     * 默认队列大小
     */
    private static final int QUEUE_SIZE = 500;

    @Bean("asyncExecutors")
    public AsyncTaskExecutor asyncExecutors() {
        ThreadPoolTaskExecutor executor = initExecutor();
        executor.setThreadNamePrefix("async_executor_thread-");
        return executor;
    }

    private ThreadPoolTaskExecutor initExecutor() {
        VisibleExecutor executor =  new VisibleExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        executor.setQueueCapacity(QUEUE_SIZE);
        executor.setAllowCoreThreadTimeOut(true);
        executor.initialize();
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }
}
